"use strict"
const express = require('express'),
    router = express.Router(),
    Category = require('../models/Category.js'),
    Content = require('../models/Content.js')

let data
router.use((req, res, next) => {
    data = {
        userInfo: req.userInfo,
        categories: []
    }
    Category.find().then(categories => {
        data.categories = categories
        next()
    })
})

router.get('/', (req, res, next) => {
    Object.assign(data, {
        category: req.query.category || '',

        count: 0,
        page: Number(req.query.page) || 1,
        limit: 1,
        pages: 0
    })

    let where = {}
    if (data.category) {
        where.category = data.category
    }
    
    Content.where(where).count().then(count => {
        data.count = count
        data.pages = Math.ceil(data.count / data.limit)
        data.page = Math.min(data.page, data.pages)
        data.page = Math.max(data.page, 1)
        const skip = (data.page - 1) * data.limit

        return Content.find().where(where).limit(data.limit).skip(skip).sort({
            addTime: -1
        })
    }).then(contents => {
        data.contents = contents
        res.render('main/index', data)
    })
})

router.get('/view', (req, res, next) => {
    const contentId = req.query.contentid || ''

    Content.findOne({
        _id: contentId
    }).then(content => {
          data.content = content

          content.views++
          content.save()
          res.render('main/view', data)
    })
})

module.exports = router